﻿using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using SmartCity.ProcessEngine.API.Domain;
using SmartCity.ProcessEngine.API.ErrorCode;
using SmartCity.ProcessEngine.API.Infrastructrue.Extensions;
using SmartCity.ProcessEngine.API.Infrastructrue.Interfaces;
using SmartCity.ProcessEngine.API.Read.Applications.Commands;
using SmartCity.ProcessEngine.API.Read.DTOS;
using System.Net.Sockets;

namespace SmartCity.ProcessEngine.API.Read.Applications.CommandHandlers
{
    /// <summary>
    /// 表单查询命令
    /// </summary>
    public class FormQueryCommandHandler : IRequestHandler<FormQueryCommand, APIResult<List<FormDTO>>>
    {
        /// <summary>
        /// 分类仓储
        /// </summary>
        private readonly IBaseRespository<WF_FromType> TypeRep;
        /// <summary>
        /// 表单仓储
        /// </summary>
        private readonly IBaseRespository<WF_Form> formRep;
        /// <summary>
        /// 行业仓储
        /// </summary>
        private readonly IBaseRespository<Industry> industyRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="typeRep">分类仓储</param>
        /// <param name="formRep">表单仓储</param>
        /// <param name="industyRep">行业仓储</param>
        public FormQueryCommandHandler(IBaseRespository<WF_FromType> typeRep,
            IBaseRespository<WF_Form> formRep,
            IBaseRespository<Industry> industyRep)
        {
            this.TypeRep = typeRep;
            this.formRep = formRep;
            this.industyRep = industyRep;
        }
        /// <summary>
        /// 请求处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<List<FormDTO>>> Handle(FormQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<FormDTO>> result = new APIResult<List<FormDTO>>();
            result.Code = APIResultCode.SearchSuccess;
            result.Message = APIResultCode.SearchSuccess.GetDescription();
         

            var res = from a in formRep.GetAll()
                      join b in TypeRep.GetAll() on a.TypeNo equals b.TypeNo
                      join c in industyRep.GetAll() on b.IndustryId equals c.IndustryId
                      where !a.IsDelete
                      select new FormDTO
                      {
                          FormId = a.FormId,
                          FormName = a.FormName,
                          FormNo=a.FormNo,
                          FormDesc=a.FormDesc,
                          TypeNo= a.TypeNo,
                          IsDelete=a.IsDelete,
                          TypeName=b.TypeName,
                          IndustryId=b.IndustryId,

                          IndustyName=c.IndustyName,

                      };
            result.Data=res.ToList();
            

            return Task.FromResult(result);
        }
    }
}
